﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using DotNet.Common.Extensions;
using System.Text;

namespace DotNet.Common.Utilities
{
    /// <summary>
    /// 文件操作工具类
    /// </summary>
    public static class FileUtilities
    {
        /// <summary>
        /// 按特定的分割符将文件数据分割到List中.
        /// </summary>
        /// <param name="fileName">文件名(全名,包含路径)</param>
        /// <param name="lineSplit">行分隔符</param>
        /// <param name="dateSplit">数据分隔符</param>
        /// <returns>数据List</returns>
        public static IList<string[]> ReadSplitFile(string fileName, string lineSplit, string dateSplit)
        {
            if (fileName.IsNullOrWhiteSpace())
                throw new ArgumentNullException("filePathName为空!");

            string allText = string.Empty;

            try
            {
                allText = System.IO.File.ReadAllText(fileName, System.Text.Encoding.Default);
            }
            catch { throw; }

            List<string[]> ls = new List<string[]>();

            var lines = Regex.Split(allText, lineSplit);

            foreach (var line in lines)
            {
                if (line != null && line.Length > 0)
                {
                    ls.Add(Regex.Split(line, dateSplit));
                }
            }
            return ls.Where(l => l.Length > 1).ToList();
        }

        /// <summary>
        /// 将CSV文件数据读取到List中
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>数据List</returns>
        public static IList<string[]> ReadCSV(string fileName)
        {
            return ReadSplitFile(fileName, Environment.NewLine, ",");
        }
    }
}
